<template>
    <div class="grey-filter">
        <input type="file" id="fileSelector"  allowexts="gif,jpeg,jpg,png,bmp" accept="image/*" @change="handleChange" />
        <div class="canver-board">
            <div class="original">
                <h5>原图</h5>
                <div class="img-wrapper">
                    <img :src="originalImg" ref="originalImg" v-show="!!originalImg" />
                </div>
            </div>
            <div class="grey">
                <h5>转换图</h5>
                <div class="img-wrapper">
                    <img :src="greyImg" v-show="!!greyImg" />
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: 'GreyFilter',
    data() {
        return {
            originalImg: '',
            greyImg: '',
        }
    },
    methods: {
        handleChange(e) {
            const file = e.target.files[0];
            const reader = new FileReader();
            const img = new Image();
            reader.readAsDataURL(file);
            const _this = this;
            reader.onload = function() {
                _this.originalImg = this.result;
                img.src = this.result;
                img.onload = function() {
                    _this.greyImg = _this.transformGrey(img);
                }
                // _this.originalImg = `data:image/png;base64,${this.result.substring(this.result.indexOf(",") + 1)}`
            }
        },
        transformGrey(imgObj) {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const imgWidth = imgObj.width;
            const imgHeight = imgObj.height;
            canvas.width = imgWidth;
            canvas.height = imgHeight;
            console.log(imgObj)
            context.drawImage(imgObj, 0, 0, imgWidth, imgHeight);
            var pixels = context.getImageData(0, 0, imgWidth, imgHeight);
            var pixelData = pixels.data;
            for(let i = 0, len = pixelData.length; i < len; i+= 4) {
                const gray = Math.floor((pixels.data[i] + pixels.data[i+1] + pixels.data[i+2])/3);
                pixels.data[i] = gray;
                pixels.data[i+1] = gray;
                pixels.data[i+2] = gray;
            }
            context.putImageData(pixels, 0, 0, 0, 0, pixels.width, pixels.height);
            return canvas.toDataURL();
        }
    }
}
</script>
<style lang="less" scoped>
    .grey-filter {
        width: 100%;
        height: 100%;
        padding: 12px;
        border: 1px solid #d5d5d5;
        .canver-board {
            display: flex;
            >div {
                flex: 1;
                margin: 12px;
            }

        }
        .img-wrapper {
            width: 100%;
            height: 85vh;
            flex: 1;
            border: 1px solid #d5d5d5;
            img {
                width: 100%;
                max-height: 100%;
            }
        }
    }
</style>